package com.example.demo.service.Impl;

import com.example.demo.entity.Student;
import com.example.demo.mapper.StudentMapper;
import com.example.demo.service.StudentService;
import com.example.demo.vo.ResponseVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;


@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
   // @Override
  //  public Object listAll() {
   //    List<Student> students=studentMapper.selectAll();
    //    return ResponseVO.success("成功查询",students);
   // }

    @Override
    public Object searchByName(String keyword) {
        List<Student> students=studentMapper.selectByName(keyword);
        if(keyword == null){
            throw new IllegalArgumentException("请输入关键字");
        }
        if (students.isEmpty()) {

            throw new IllegalArgumentException("未找到相关学生");

        }
        return ResponseVO.success("成功查询到：",students);
    }

    @Override
    public Student getById(Integer id) {
        Student student = studentMapper.selectById(id);
        if (id == null) {

            throw new IllegalArgumentException("学生ID不能为空");

        }
        if (id <= 0) {

            throw new IllegalArgumentException("学生ID必需大于等于1");

        }
        if(student == null){
            throw new IllegalArgumentException("所查学生不存在");
        }
        return  student;
    }

    @Override
    @Transactional
    public int insert(Student student) {
        if(student.getName() == null || student.getName().trim().isEmpty() )
        {
            throw new IllegalArgumentException("所增加的名字不能为空");
        }
        if(student.getAge()<=0){
            throw new IllegalArgumentException("年龄必需大于0");
        }
        return studentMapper.insert(student);
    }

    @Override
    public int update(Student student) {
        //查询所改学生是否存在
        Student exist=studentMapper.selectById(student.getId());
        if(exist == null){
            throw new IllegalArgumentException("您要修改的学生不存在");
        }
        return studentMapper.update(student);
    }

    @Override
    public int delete(Integer id) {
        //查询所删学生是否存在
        Student exist=studentMapper.selectById(id);
        if(exist == null){
            throw new IllegalArgumentException("您要删除的学生不存在");
        }
        return studentMapper.delete(id);
    }

    @Override
    public PageInfo<Student> listByPage(int pageNum, int pageSize, String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        List<Student> students = studentMapper.selectByKeyword(keyword);
        return new PageInfo<>(students);
    }


}
